package com.sam.im.sms.index.activitys;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract.PhoneLookup;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.SmsManager;
import android.telephony.SubscriptionManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lqr.emoji.EmotionKeyboard;
import com.lqr.emoji.EmotionLayout;
import com.lqr.emoji.IEmotionSelectedListener;
import com.sam.im.sms.R;
import com.sam.im.sms.beans.ThreadDetailBean;
import com.sam.im.sms.index.adapters.MyThreadDetailAdapter;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 发送短信的2种方法
 * 发送广播、对方受到广播
 * 监听数据库变化的广播，以及内容观察着
 * 推荐 http://www.itnose.net/detail/6132802.html
 *
 * @author wyf
 */
public class ThreadDetailActivity extends AppCompatActivity {
    private static final String TAG = "ThreadDetailActivity";
    private static String SMS_SEND_ACTIOIN = "SMS_SEND_ACTIOIN";
    private static String SMS_DELIVERED_ACTION = "SMS_DELIVERED_ACTION";
    @Bind({R.id.mThreadListView})
    RecyclerView mListView;
    @Bind(R.id.txt_sim1)
    TextView txtSim1;
    @Bind(R.id.ll_send_layout_sim1)
    LinearLayout llSendLayoutSim1;
    @Bind(R.id.txt_sim2)
    TextView txtSim2;
    @Bind(R.id.ll_send_layout_sim2)
    LinearLayout llSendLayoutSim2;
    private String phone;
    @Bind(R.id.name)
    TextView name;
    private MyThreadDetailAdapter mThreadDetailAdapter;
    private ArrayList<ThreadDetailBean> mDatas;
    private Uri uri = Uri.parse("content://sms/");
    private String[] projection = new String[]{"_id", "address", "person",
            "body", "type", "date"};
    private String[] contactProjection = new String[]{PhoneLookup._ID, PhoneLookup.DISPLAY_NAME};
    @Bind(R.id.ed_context)
    EditText sms_content;
    @Bind(R.id.elEmotion)
    EmotionLayout mElEmotion;
    @Bind(R.id.ivEmo)
    ImageView mIvEmo;
    private EmotionKeyboard mEmotionKeyboard;
    @Bind(R.id.llContent)
    LinearLayout llContent;
    private boolean isState = false;
    String message;
    private int subIdOne, subIdTwo;


    MySendBr sendBr = new MySendBr();
    MyDeliverBr deliverBr = new MyDeliverBr();
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    private mySmsContentObserver observer = new mySmsContentObserver(new Handler());

    @Override
    protected void onResume() {
        super.onResume();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    @OnClick({R.id.ll_send_layout_sim1, R.id.ll_send_layout_sim2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_send_layout_sim1:
                if (ContextCompat.checkSelfPermission(ThreadDetailActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ThreadDetailActivity.this, new String[]{Manifest.permission.SEND_SMS}, 1000);
                } else if (ContextCompat.checkSelfPermission(ThreadDetailActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ThreadDetailActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 1000);
                } else {
                    sendMsg();
                }
                break;
            case R.id.ll_send_layout_sim2:
                if (ContextCompat.checkSelfPermission(ThreadDetailActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ThreadDetailActivity.this, new String[]{Manifest.permission.SEND_SMS}, 1000);
                } else if (ContextCompat.checkSelfPermission(ThreadDetailActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ThreadDetailActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 1000);
                } else {
                    isState = false;
                    sendMsg();
                }
                break;
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    class mySmsContentObserver extends ContentObserver {

        public mySmsContentObserver(Handler handler) {
            super(handler);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onChange(boolean selfChange) {
            // TODO Auto-generated method stub
            super.onChange(selfChange);
            init();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    class MySendBr extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SMS_SEND_ACTIOIN)) {
                try {
                    switch (getResultCode()) {
                        case RESULT_OK:
                            Toast.makeText(context, getResources().getString(R.string.str_sms_sent_success), Toast.LENGTH_SHORT).show();
                            ContentValues values = new ContentValues();
                            values.put("address", formatPhoneNum(phone));
                            values.put("person", "");
                            values.put("protocol", "0");
                            values.put("read", "1");
                            values.put("type", "2");
                            values.put("body", message);
                            context.getContentResolver().insert(Uri.parse("content://sms/"), values);
                            sms_content.setText("");
                            break;
                        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                            Toast.makeText(context, getResources().getString(R.string.str_sms_sent_failed), Toast.LENGTH_SHORT).show();
                            break;
                        case SmsManager.RESULT_ERROR_RADIO_OFF:
                            break;
                        case SmsManager.RESULT_ERROR_NULL_PDU:
                            break;
                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            } else if (intent.getAction().equals(SMS_DELIVERED_ACTION)) {
                try {
                    switch (getResultCode()) {
                        case RESULT_OK:
                            break;
                        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                            Toast.makeText(context, getResources().getString(R.string.str_sms_rec_failed), Toast.LENGTH_SHORT).show();
                            break;
                        case SmsManager.RESULT_ERROR_RADIO_OFF:
                            break;
                        case SmsManager.RESULT_ERROR_NULL_PDU:
                            break;

                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
        }

    }

    class MyDeliverBr extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && intent.getAction().equals("DELIVERED_SMS_ACTION")) {
                Toast.makeText(context, "deliverd ok", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "myDeliverd");
            }
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.thread_detail);
        ButterKnife.bind(this);
        //动态注册2个广播--发送成功，对方接收成功
        registerReceiver(sendBr, new IntentFilter(SMS_SEND_ACTIOIN));
        registerReceiver(deliverBr, new IntentFilter(SMS_DELIVERED_ACTION));
        //受到系统的短信 注册短信数据库变化通知的。。
        getContentResolver().registerContentObserver(uri, true, observer);
        init();
        initListener();
    }

    private void initListener() {
        llContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        closeBottomAndKeyboard();
                        break;
                }
                return false;
            }
        });
    }

    private void closeBottomAndKeyboard() {
        mElEmotion.setVisibility(View.GONE);
        if (mEmotionKeyboard != null) {
            mEmotionKeyboard.interceptBackPress();
        }
    }

    private void initEmotionKeyboard() {
        mEmotionKeyboard = EmotionKeyboard.with(this);
        mEmotionKeyboard.bindToContent(llContent);
        mEmotionKeyboard.bindToEmotionButton(mIvEmo);
        mEmotionKeyboard.bindToEditText(sms_content);
        mEmotionKeyboard.setEmotionLayout(mElEmotion);

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    private void init() {
        if (SubscriptionManager.from(this).getActiveSubscriptionInfoCount() == 1) {
            isState = true;
            txtSim1.setVisibility(View.GONE);
            llSendLayoutSim2.setVisibility(View.GONE);
        } else {
            isState = false;
        }
        initEmotionKeyboard();
        mElEmotion.attachEditText(sms_content);
        mElEmotion.setEmotionSelectedListener(new IEmotionSelectedListener() {
            @Override
            public void onEmojiSelected(String key) {

            }

            @Override
            public void onStickerSelected(String categoryName, String stickerName, String stickerBitmapPath) {
                String stickerPath = stickerBitmapPath;
                Toast.makeText(getApplicationContext(), stickerPath, Toast.LENGTH_SHORT).show();
            }
        });
        Intent intent = getIntent();
        if (intent != null) {
            phone = intent.getStringExtra("phone");
        }
        //data--数据库中获取!!!!
        Cursor threadDetailCursor = getContentResolver().query(uri, projection, "address=?", new String[]{phone}, "date desc");
        praseThreadDetailCursor(threadDetailCursor);
        Collections.reverse(mDatas);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setStackFromEnd(true);
        mListView.setLayoutManager(manager);
        //适配器
        mThreadDetailAdapter = new MyThreadDetailAdapter(this, mDatas);
        //设置适配器
        mListView.setAdapter(mThreadDetailAdapter);

    }

    private void praseThreadDetailCursor(Cursor threadDetailCursor) {
        mDatas = new ArrayList<ThreadDetailBean>();
        if (threadDetailCursor != null && threadDetailCursor.getCount() > 0) {
            while (threadDetailCursor.moveToNext()) {
                String address = threadDetailCursor.getString(threadDetailCursor.getColumnIndex("address"));
                String body = threadDetailCursor.getString(threadDetailCursor.getColumnIndex("body"));
                String type = threadDetailCursor.getString(threadDetailCursor.getColumnIndex("type"));
                String date = threadDetailCursor.getString(threadDetailCursor.getColumnIndex("date"));

                //type為1是对方的item，为2是自己的itme
                //通过电话获取联系人的姓名
                String contactName = null;
                Uri contactNameUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address));
                Cursor contactNameCursor = getContentResolver().query(contactNameUri, contactProjection, null, null, null);
                if (contactNameCursor != null && contactNameCursor.moveToFirst()) {
                    contactName = contactNameCursor.getString(1);
                }

                Log.i(TAG, "address" + address + ",body" + body + ",type" + type + ",date" + date + ",contactName" + contactName);
                if (type.equals("1")) {
                    //对方
                    ThreadDetailBean heiBean = null;
                    if (contactName != null) {
                        heiBean = new ThreadDetailBean(contactName, date, body, R.layout.hei_item);
                    } else {
                        heiBean = new ThreadDetailBean(address, date, body, R.layout.hei_item);

                    }
                    mDatas.add(heiBean);
                } else {
                    //自己
                    ThreadDetailBean mBean = new ThreadDetailBean(null, date, body, R.layout.me_item);
                    mDatas.add(mBean);
                }
                if (contactName != null) {
                    name.setText(contactName);
                } else {
                    name.setText(address);
                }

            }

        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    private void sendMsg() {
        String smsContent = sms_content.getText().toString().trim();
        if (smsContent.equals("")) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            SubscriptionManager subscriptionManager = (SubscriptionManager) getSystemService(TELEPHONY_SUBSCRIPTION_SERVICE);
            Class sclass = subscriptionManager.getClass();
            Method getSubId = null;
            try {
                getSubId = sclass.getDeclaredMethod("getSubId", int.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            int[] ints = new int[1];
            try {
                ints = (int[]) getSubId.invoke(subscriptionManager, 0);
                subIdOne = ints[0];
                ints = (int[]) getSubId.invoke(subscriptionManager, 1);
                subIdTwo = ints[0];
            } catch (Exception e) {
                e.printStackTrace();
            }
            //动态注册2个广播--发送成功，对方接收成功
            Intent mySendIntent = new Intent(SMS_SEND_ACTIOIN);
            Intent myDeliverIntent = new Intent(SMS_DELIVERED_ACTION);
            PendingIntent sentIntent = PendingIntent.getBroadcast(ThreadDetailActivity.this, 0, mySendIntent, 0);
            PendingIntent deliveryIntent = PendingIntent.getBroadcast(ThreadDetailActivity.this, 0, myDeliverIntent, 0);
            if (isState) {
                SmsManager smsManager = SmsManager.getDefault();
                ArrayList<String> divideContents = smsManager.divideMessage(smsContent);
                for (String msg : divideContents) {
                    message = msg;
                    smsManager.sendTextMessage(formatPhoneNum(phone), null, msg, sentIntent, deliveryIntent);
                }
            } else {
                SmsManager smsManager = SmsManager.getSmsManagerForSubscriptionId(subIdTwo);
                ArrayList<String> messages = SmsManager.getDefault().divideMessage(smsContent);
                for (String msg : messages) {
                    message = msg;
                    smsManager.sendTextMessage(formatPhoneNum(phone), null, msg, sentIntent, deliveryIntent);
                }
            }
        }
    }
    /**
     * 去掉手机号内除数字外的所有字符
     *
     * @param phoneNum 手机号
     * @return
     */
    private String formatPhoneNum(String phoneNum) {
        String regex = "(\\+86)|[^0-9]";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phoneNum);
        return matcher.replaceAll("");
    }

    @Override
    public void onBackPressed() {

        if (mElEmotion.isShown()) {
            mEmotionKeyboard.interceptBackPress();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(sendBr);
        unregisterReceiver(deliverBr);
    }
}